package com.test;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.concurrent.BlockingQueue;

public class AlarmConsumer implements Runnable {
	private final BlockingQueue<AlarmInfo> alarmQueue;
	private final Socket sock;
	public AlarmConsumer(BlockingQueue<AlarmInfo> queue, Socket sock){
		alarmQueue=queue;
		this.sock=sock;
	}
	public void run() {
		System.out.println("Consumer thread start...."+alarmQueue.size());
		boolean isExit = true;
		AlarmInfo alarm = null;
		try{
			while(isExit){
				if(sock.isBound()){
				alarm = alarmQueue.take();
				sendAlarm(alarm);
				}
			}
		}catch(Exception e){
			System.out.print("shut down alarmConsumer thread.");
			try {
				alarmQueue.put(alarm);
				System.out.println("after thread exit.:"+alarmQueue.size());
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			isExit = false;
			System.out.print("shut down alarmConsumer thread.");
			Thread.currentThread().interrupt();
			return;
		}
	}
	
	public void sendAlarm(AlarmInfo alarm)throws Exception{
		PrintWriter wtr = null;
		try {
			wtr = new PrintWriter(sock.getOutputStream());
			wtr.write(alarm.toString());
			wtr.flush();
			System.out.println("send data......");
		} catch (IOException e) {
			throw new Exception(e);
//			e.printStackTrace();
		}  
	}

}
